/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2008-2011, Salzburg Research. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of the KiWi Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributor(s):
 *  Thomas Kurz
 *
 * File Info:
 *   User: Thomas Kurz
 *   Date: 2011/02/16
 *   Time: 09:46
 *
 * Project: KiWi2, KiWi2 module
 */
$.kiwi2 = $.kiwi2 || {};
$.widget("kiwi2.queryexplorer", {
    /**
     * is called when widget gets initialized
     */
    _init: function(){
        this.initContainer();
        this.initContent();
    },

    /**
     * build html environment for the widget
     */
    initContainer: function() {
        var that = this;
        var widget = $("<div/>",{"class":"widget ui-widget"});
        this.contentBox = $("<div/>",{"class":"widget-content ui-widget-content"});
        this.contentBox.text(this.options.labels.loading[this.options.lang]);
        var headerBox = $("<div/>",{"class":"widget-header ui-widget-header"});
        var header = $("<h3/>");
        var buttons = $("<div/>",{"style":"float:right;margin-top:-18px;margin-right:2px;"});
        this.blinder = $("<button/>",{"class":"small-button"});
        this.blinder.text(this.options.labels.showhide[this.options.lang])
        this.blinder.button({icons: {primary: "ui-icon-minus"},text:false});
        this.blinder.click(function(){
            that.hideContent();
        });
        buttons.append(this.blinder);
        header.text(this.options.labels.title[this.options.lang]);
        this.element.html("");
        widget.appendTo(this.element);
        headerBox.appendTo(widget);
        this.contentBox.appendTo(widget);
        header.appendTo(headerBox);
        buttons.appendTo(headerBox);
    },

    initContent: function() {
        var that = this;
        this.queryBox = $("<textarea rows='5' style='width:100%'/>");
        var table = $("<table style='width:100%;'/>");
        var tr = $("<tr/>");
        var td1 = $("<td style='text-align:left;'/>");
        var td2 = $("<td style='text-align:right;'/>");
        table.append(tr);
        tr.append(td1);
        tr.append(td2);

        //left side
        var label1 = $("<label for='queryType' style='padding-right:3px'>Query:</label>");
        this.selectQT = $("<select name='queryType'><option value='solr'>solr</option><option value='sparql'>sparql</option>");
        for(var i=0; i<this.options.solrlang.length;i++) {
            this.selectQT.append($("<option value='solr&lang="+this.options.solrlang[i]+"'>solr("+this.options.solrlang[i]+")</option>"))
        }
        var label2 = $("<label for='queryType' style='padding-right:3px;padding-left:15px'>Results:</label>");
        this.selectWT = $("<select name='queryType'><option>browse</option><option>json</option><option>xml</option>");
        td1.append(label1);
        td1.append(this.selectQT);
        td1.append(label2);
        td1.append(this.selectWT);

        //right side
        var reset = $("<button style='margin-right:5px;'/>");
        reset.text(this.options.labels.reset[this.options.lang])
        reset.button({icons: {primary: "ui-icon-cancel"},text:true});
        reset.click(function(){
            that.reset();
        });
        td2.append(reset);
        var ok = $("<button/>");
        ok.text(this.options.labels.run[this.options.lang])
        ok.button({icons: {primary: "ui-icon-search"},text:true});
        ok.click(function(){
            that.run();
        });
        td2.append(ok);

        //errors and hints
        this.error = $("<div/>");

        //results
        this.results = $("<div/>");
        //append
        this.contentBox.text("");
        this.contentBox.append(this.queryBox);
        this.contentBox.append(table);
        this.contentBox.append(this.error);
        this.contentBox.append(this.results);
        //TODO select box should be replaced by ui menu as soon as available (version 1.9?)
    },

    /*
    openErrorDialog: function(text) {
        var icon = "<span style='float: left; margin-right: 0.3em;' class='ui-icon ui-icon-alert'></span>";
        var message = $("<div  class='ui-widget' style='display:none'><div class='ui-state-error ui-corner-all'><p>"+icon+text+"</p></div></div>");
        this.error.append(message);
        message.show("blind",function(){
            setTimeout(function(){message.hide("blind")},5000);
        });
    },
    */

    run: function() {
        var that = this;
        //get and encode params
        var qt = this.selectQT.val();
        var wt = this.selectWT.val();
        var q = this.queryBox.val();
        if(wt == "browse") {
            wt = "json";
        }
        if(q=="") {
            alert(this.options.labels.query__not_empty[this.options.lang]);
            return;
        }
        //build url
        q = encodeURIComponent(q);
        url = this.options.host+"/search/select?q="+q+"&wt="+wt+"&qt="+qt;
        if(this.selectWT.val() == "browse") {
            jQuery.ajax({
                type: "GET",
                url: url,
                success: function(data){
                    if(qt == "sparql") {
                        that.showSparqlResult(data);
                    } else {
                        that.showSolrResult(data);
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    alert("Error");
                }
            });
        } else {
            window.location = url;
        }
    },

    reset : function() {
        this.queryBox.val("");
        this.selectQT.val("solr");
        this.selectWT.val("browse");
        this.results.html("");
    },

    showSparqlResult : function(data) {
        if(data.results.bindings.length == 0) {
           this.results.html("<h3>"+this.options.labels.noresults[this.options.lang]+"</h3>")
        } else {
           this.results.html("<h3>"+this.options.labels.results[this.options.lang]+":</h3>");
           var table = $("<table style='width:100%'/>");
           var head = $("<tr/>");
           //header
           for(var i=0; i<data.head.vars.length;i++) {
                head.append("<td>"+data.head.vars[i]+"</td>")
           }
           table.append(head);
           //results
           var that = this;

           var newUri = function(uri) {
              var x = $("<a>"+uri+"</a>");
              x.click(function(){that.showResource(uri)});
              return x;
           }

           for(var i=0; i<data.results.bindings.length;i++) {
               var row = $("<tr/>");
               var d = data.results.bindings[i];
               for(var j=0; j<data.head.vars.length;j++) {
                   var v = d[data.head.vars[j]];
                   var x;
                   if(v.type == "uri") {
                        x = newUri(v.value);
                   } else if(v.type == "literal") {
                        x = v.value;
                   } else {
                       //TODO other types? bnode?
                   }
                   var td = $("<td/>");
                   td.append(x);
                   row.append(td);
               }
               table.append(row);
           }
           this.results.append(table);
        }
    },

    showSolrResult : function(data) {
        alert("solr:"+data);
    },

    showResource : function(url) {
        var that = this;
        alert(url);
        jQuery.ajax({
            type: "GET",
            url: url,
            success: function(data) {
                var subjects = [];
                for (property in data) {
                    subjects.push(data);
                }
                if (subjects.length == 0) {
                    that.results.html("<h3>" + that.options.labels.noresource[that.options.lang] + " " + url + "</h3>");
                } else {
                    that.results.html("<h3>" + that.options.labels.resource[that.options.lang] + " " + url + "</h3>");
                }
                //TODO write out
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("not available via webservice");
            }
        });

    },


    /**
     * if widget is hidden, then show it and vice versa
     */
    hideContent: function() {alert(this.selectQT.val());
        var that = this;
        if(this.contentBox.is(":visible")) {
            this.contentBox.hide("blind",function(){
                that.blinder.button({icons: {primary:"ui-icon-plus"}});
            });
        }
        else {
            this.contentBox.show("blind",function(){
                that.blinder.button({icons: {primary:"ui-icon-minus"}});
            })
        }
    },
        /**
     * this are the options that customize the widget
     */
    options: {
	    host: 'http://localhost:8080/KiWi2',
        labels: {"title":{"de":"Query Explorer","en":"Query Explorer"},
                 "loading":{"de":"Laden...","en":"Loading..."},
                 "run":{"de":"Ausführen","en":"Run"},
                 "reset":{"de":"Zurücksetzen","en":"Reset"},
                 "ok":{"de":"OK","en":"OK"},
                 "error":{"de":"Fehler","en":"Error"},
                 "cancel":{"de":"Abbrechen","en":"Cancel"},
                 "noresults":{"de":"Keine Ergebnisse","en":"No results"},
                 "query__not_empty":{"de":"Anfrage darf nicht leer sein","en":"Query may not be empty"},
                 "results":{"de":"Ergebnisse","en":"Results"},
                 "resource":{"de":"Ressource","en":"Resource"},
                 "noresource":{"de":"Keine Triple für Ressource","en":"No triples for resource"},
                 "showhide":{"de":"Aus-/Einblenden","en":"Show/Hide"}
                 },
        "solrlang":["de","en"],
        lang: "de"
    }
});
